//
//  NetworkFunctions.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/23.
//

import Foundation
import Moya

//接口返回统一处理,filterCode为指定错误吗，当错误吗为filterCode的时候，返回正确
func dealNetResult<T: Codable>(result: (Result<Response, MoyaError>), modeType: T.Type ,filterCode: [Int] = [], suc: @escaping (T) -> Void, fail:@escaping(Error) -> Void) {
    switch result {
    case .success(object: let response):
        if (200...299).contains(response.statusCode) {
            do {
                if modeType is Data.Type {
                    //如果是Data类型，直接返回
                    suc(response.data as! T)
                    return
                }
                let decoder = JSONDecoder()
                let str = toString(jsonData: response.data) ?? ""
                showLog("接口返回数据：\(str)")
                if modeType is String.Type {
                    //String 类型直接返回
                    suc(str as! T)
                } else {
                    let bean = try decoder.decode(modeType, from: response.data)
                    suc(bean)
                }
            } catch{
                fail(MyError.getJsonFaild)
            }
        } else {
            showLog(response)
            let str = toString(jsonData: response.data) ?? ""
            if filterCode.contains(response.statusCode) {
                //有用到filterCode的，必须要String类型，不然也是报错
                if modeType is String.Type {
                    suc(str as! T)
                } else {
                    fail(MyError.netFail(response.statusCode, str))
                }
            } else {
                showLog("接口报错：\(response.statusCode)")
                showLog("接口报错：\(str)")
                fail(MyError.netFail(response.statusCode, str))
            }
           
        }
        break
    case .failure(error: let error):
        fail(error)
        break
    }
}
